package com.user.service.Impl;

import DO.user.UserDO;
import DTO.EditPasswordDTO;
import DTO.UserLoginDTO;
import VO.EditUserMsgVO;
import VO.Feight.ChatByUserMsgVO;
import VO.Feight.CommentUserMsgVO;
import VO.Feight.UserMsgByChatVO;
import VO.UserMsgVO;
import com.feign.clients.ChatClient;
import com.user.mapper.FensMapper;
import com.user.mapper.UserMapper;
import com.user.service.UserService;
import com.utils.PasswordUtil;
import Exception.BaseException;
import Exception.UserNotExistException;
import Exception.PasswordIsNOTRightException;
import constant.CodeConstant;
import constant.MsgConstant;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.Result;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.utils.AgeCalculator.calculateAge;
import static com.utils.PasswordUtil.generateRandomSalt;
import static com.utils.PasswordUtil.getSHA256Hash;
import static com.utils.StringUtils.extractFilename;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FensMapper fensMapper;

    @Autowired
    private ChatClient chatClient;

    // 密码登录 密码错误 0，正确 用户id，该手机号未注册 -1
    public Integer LoginByPassword(UserLoginDTO userLoginDTO) {
        // 1. 先根据手机号去查询出这个人的密码
        UserDO userDO = userMapper.getUser(userLoginDTO.getPhoneNumber());

        // 2. 判断数据库中有无这个用户
        if (userDO == null){
            return -1;
        }

        // 3. 进行密码比对
        if (!Objects.equals(userDO.getPassword(),
                PasswordUtil.getSHA256Hash(userDO.getSalt(), userLoginDTO.getPassword()))){
            // 表示密码不正确
            return 0;
        }

        return userDO.getId();
    }

    // 用户登录获取id，当用户为注册时自动为该用户进行注册
    public Integer userRegistered(UserLoginDTO userLoginDTO) {
        // 1. 先查询数据库中有无此人
        UserDO userDO = userMapper.getUser(userLoginDTO.getPhoneNumber());
        if (userDO !=null){
            return userDO.getId();
        }
        // 当数据库中没有这个人的时候，需要将这个人的信息进行注册
        UserDO userDO1 = new UserDO();

        userDO1.setPhoneNumber(userLoginDTO.getPhoneNumber());
        userDO1.setCreatedTime(LocalDateTime.now());
        userMapper.insert(userDO1);
        return userDO1.getId();
    }

    // 保存用户头像地址信息
    public void saveAvatar(String path, Integer userId) {
        userMapper.saveAvatar(path,userId);
    }

    // 获取文件地址
    public String getAvatar(String userId) {
        return userMapper.getAvatar(userId);
    }

    // 获取用户信息
    public UserMsgVO getUserMsg(String userId) {
        UserMsgVO userMsgVO = userMapper.getMsg(userId);
        userMsgVO.setFensNumber(fensMapper.getFensNumber(userId));
        userMsgVO.setFollowNumber(fensMapper.getFollowNumber(userId));
        // 发起远程调用获取用户的作品数
        UserMsgByChatVO chatNumberAndLikeNumber = chatClient.getChatNumberByUserId(Integer.valueOf(userId));
        userMsgVO.setChatNumber(chatNumberAndLikeNumber.getChatNumber());
        userMsgVO.setChatLikeNumber(chatNumberAndLikeNumber.getChatLikeNumber());
        // 计算年龄
        if (!(userMsgVO.getYear()==null ||
            userMsgVO.getMonth()==null||
            userMsgVO.getDay()==null)){
            userMsgVO.setAge(calculateAge(userMsgVO.getYear(),userMsgVO.getMonth(),userMsgVO.getDay()));
        }
        return userMsgVO;
    }

    // 修改用户信息
    public void editUserMsg(String userId, EditUserMsgVO editUserMsgVO) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(editUserMsgVO,userDO);
        userDO.setId(Integer.valueOf(userId));
        userMapper.editUserMsg(userDO);
    }

    // 判断用户是否存在
    public boolean getUserExist(Integer id) {
        int isExist = userMapper.getIsExist(id);
        return isExist==1;
    }

    // 获取用户密码类型
    public Integer getPasswordType(Integer userId) {
        UserDO userDO = userMapper.getById(userId);
        if (userDO==null){
            throw new UserNotExistException();
        }
        if (userDO.getPassword()==null){
            return 0;
        }
        return 1;
    }

    // 获取用户手机号
    public String getUserPhone(Integer userId) {
        return userMapper.getUserPhone(userId);
    }

    // 保存用户密码
    public void savePassword(String newPassword, Integer userId) {
        UserDO userDO = userMapper.getById(userId);
        if (userDO.getPassword()!=null){
            // 表示该用户有密码，不能修改
            throw new BaseException();
        }
        // 盐
        String salt = generateRandomSalt();
        String password = getSHA256Hash(salt, newPassword);
        userMapper.savePassword(salt,password,userId);
    }

    // 用户修改密码
    public void updatePassword(EditPasswordDTO editPasswordDTO, Integer userId) {
        // 1. 进行密码比较
        UserDO userDO = userMapper.getById(userId);
        if (Objects.equals(userDO.getPassword(),
                PasswordUtil.getSHA256Hash(userDO.getSalt(), editPasswordDTO.getOldPassword()))){

            // 比对成功，进行新密码的设置
            String salt = generateRandomSalt();
            String password = getSHA256Hash(salt, editPasswordDTO.getNewPassword());
            userMapper.savePassword(salt,password,userId);
            return;
        }
        throw new PasswordIsNOTRightException("密码不正确");
    }

    // 获取帖子信息时返回的用户信息
    public Result<ChatByUserMsgVO> getChatUserMsg(Integer chatUserId, Integer userId) {
        UserDO userDO = userMapper.getById(chatUserId);

        if (userDO==null){
            return Result.error("用户不存在",201);
        }

        ChatByUserMsgVO chatByUserMsgVO = new ChatByUserMsgVO();
        chatByUserMsgVO.setUsername(userDO.getUserName());

        // userId 为0表示游客登录
        if (userId==0){
            chatByUserMsgVO.setFollow(0);
        }else {
            chatByUserMsgVO.setFollow(fensMapper.getIsFollow(chatUserId,userId));
        }
        return Result.success(chatByUserMsgVO);
    }

    // 获取用户的头像以及昵称消息
    public Result<CommentUserMsgVO> getCommentUserMsg(Integer userId) {
        UserDO userDO = userMapper.getById(userId);
        if (userDO ==null){
            // 表示用户不存在 14 用户不存在
            return Result.error(MsgConstant.USER_IS_NOT_EXIST, CodeConstant.USER_NOT_EXIST);
        }
        CommentUserMsgVO commentUserMsgVO = new CommentUserMsgVO();
        if (userDO.getUserName() != null){
            commentUserMsgVO.setUsername(userDO.getUserName());
        }
        if (userDO.getAvatar()!=null){
            commentUserMsgVO.setAvatar(extractFilename(userDO.getAvatar()));
        }
        return Result.success(commentUserMsgVO);
    }

}
